using System.ComponentModel.DataAnnotations;
using BootBlazor.Servers.Auth;
using BootBlazor.Servers.Helper;
using BootBlazor.Servers.Resources;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using MudBlazor;

namespace BootBlazor.Servers.Components.Dialogs;

public partial class ConfirmUserPasswordDialog
{
    private Dictionary<string, object> _inputAttributes =
        new Dictionary<string, object>()
            {
               { "autocomplete", "new-password2" },
            };

    private PasswordModel _passwordModel = new PasswordModel();

    [CascadingParameter] IMudDialogInstance? MudDialog { get; set; }

    [Inject] public AuthenticationStateProvider? AuthStateProvider { get; set; }

    [Parameter] public EventCallback<CommonDialogEventArgs> ConfirmCallBack { get; set; }

    private async Task ConfirmPassword()
    {
        using var context = await _dbFactory.CreateDbContextAsync();

        var userId = await AuthStateProvider!.GetUserIdAsync();
        var user = context.Users.Find(userId);
        if (user == null)
        {
            _snackbarService.Add(_loc["NotFindUser"], Severity.Error);
            MudDialog?.Close(DialogResult.Cancel());
            return;
        }
        var isPwdValid = HashHelper.VerifyPassword(user.PasswordHash, _passwordModel.Password!);
        if (!isPwdValid)
        {
            _snackbarService.Add(_loc["PasswordValidFail"], Severity.Error);
            MudDialog?.Close(DialogResult.Cancel());
            return;
        }

        await ConfirmCallBack.InvokeAsync(new CommonDialogEventArgs());
        MudDialog?.Close(DialogResult.Ok(true));
    }

    private class PasswordModel
    {
        [Required(ErrorMessageResourceName = "Login_PasswordHelpText",
            ErrorMessageResourceType = typeof(CusCulture))]
        public string? Password { get; set; }
    }

}
